<template>
  <div>
    <el-dialog
        :title="isGlobal?'全局场景': '终端场景'"
        :visible.sync="show"
        width="60%"
        :before-close="handleClose">
      <div v-if="show">
        <el-steps align-center style="margin-bottom: 15px;" :space="400" :active="step" finish-status="success">
          <el-step title="选择终端"></el-step>
          <el-step title="配置场景"></el-step>
          <el-step title="创建场景"></el-step>
        </el-steps>
        <div v-show="step == 1">
          <CommonTable
              class="commonTable"
              ref="terminalTableRef"
              :is-all-selection="false"
              :is-selection="true"
              row-key="id"
              :is-show-index="false"
              :is-has-opera="false"
              :t-column-data="terminalListCol"
              :remote-api="getList"
              :is-reserve-select="true"
              @changeRow="changeFileRowMethods"
              operating-width="180px"
          >

          </CommonTable>
        </div>

        <div v-if="step == 2">
          <div v-show="sceneBaseForm.state == 1">
            <el-form>
              <el-form-item label="统一投放">
                <el-switch
                  v-show="isGlobal"
                  v-model="sceneBaseForm.state"
                  active-value="1"
                  inactive-value="0"
                >
                </el-switch>
              </el-form-item>
            </el-form>
          </div>
          <!--不是统一投放-->
          <el-table
              :data="selectTerminal"
              border
              v-show="sceneBaseForm.state == 0"
              style="width: 100%">
            <el-table-column
                prop="name"
                label="终端名称"
                width="180">
            </el-table-column>

            <el-table-column
                label="窗口布局"
                width="180">
              <template slot-scope="scope">
                <el-select :key="selectKeys" @change="changeLayoutId(scope.row, 'selectTerminal', scope.$index)" v-model="scope.row.layoutId" placeholder="请选择">
                  <el-option
                    v-for="item in layoutList"
                    :key="item.id"
                    :label="item.title"
                    :value="item.id">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>

            <el-table-column
                prop="mediaName"
                label="窗口内容"
                width="280">
            </el-table-column>
            <el-table-column
                label="操作"
            >
              <template slot-scope="scope">
                <el-button type="primary" @click="startSettingWindow(scope.row, scope.$index)">配置</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!--统一投放显示-->
          <el-table
            :data="selectGlobalPutTerminal"
            v-show="sceneBaseForm.state == 1"
            border
            style="width: 100%">
            <el-table-column
              prop="name"
              label="终端名称"
              width="180">
            </el-table-column>

            <el-table-column
              label="窗口布局"
              width="180">
              <template slot-scope="scope">
                <el-select :key="selectKeys" @change="changeLayoutId(scope.row, 'selectGlobalPutTerminal', scope.$index)" v-model="scope.row.layoutId" placeholder="请选择">
                  <el-option
                    v-for="item in layoutList"
                    :key="item.id"
                    :label="item.title"
                    :value="item.id">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>

            <el-table-column
              prop="mediaName"
              label="窗口内容"
              width="280">
            </el-table-column>
            <el-table-column
              label="操作"
            >
              <template slot-scope="scope">
                <el-button type="primary" @click="startSettingWindow(scope.row, scope.$index)">配置</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div v-if="step == 3">
          <el-form ref="form" :model="sceneBaseForm" label-width="80px">
            <el-form-item label="场景名称">
              <el-input v-model="sceneBaseForm.title"></el-input>
            </el-form-item>
            <el-form-item label="缩略图">
              <el-upload
                  style="width: 100%;height: 100%"
                  :show-file-list="false"
                  class="upload-demo"
                  drag
                  :on-success="uploadSuccess"
                  :action="uploadUrl"
              >
                <div v-if="!this.sceneBaseForm.image">
                  <i class="el-icon-upload"></i>
                  <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                </div>
                <img style="width: 100%;height: 100%;" v-if="this.sceneBaseForm.image" :src="this.sceneBaseForm.image" alt="">
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" v-if="step > 1" @click="prevStepMethods">上一步</el-button>
        <el-button type="primary" @click="confirmSubmit">
          {{step != 3?'下一步': '确 定'}}
        </el-button>
      </span>
    </el-dialog>

    <el-dialog
        title="配置窗口内容"
        :visible.sync="isShowWindowContent"
        width="60%"
        :before-close="closeWindowContent">
      <div>
        <el-table
            :data="sceneWindowList"
            border
            style="width: 100%">
          <el-table-column
              label="窗口序号"
              type="index"
              width="120">
          </el-table-column>

          <el-table-column
              label="窗口位置"
              width="180">
            <template slot-scope="scope">
              <div class="row-container" v-for="(item, index) in scope.row.horizontal">
<!--                {{scope.row}}-->
                <div v-if="scope.row.title == '二分屏'" :class="childIndex == scope.row.x?'col-container col-container-active': 'col-container'" v-for="(childItem, childIndex) in scope.row.vertical"></div>
                <div v-if="scope.row.title != '二分屏'" :class="index == scope.row.x && childIndex == scope.row.y?'col-container col-container-active': 'col-container'" v-for="(childItem, childIndex) in scope.row.vertical"></div>
              </div>
            </template>
          </el-table-column>

          <el-table-column
              prop="date"
              label="内容类型"
              width="180">
            <template slot-scope="scope">
              <el-select @change="(val) => changeTypeMethods(val, scope.$index)" v-model="scope.row.mediaType" placeholder="请选择">
                <el-option
                  v-for="item in fileTypeMap"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
              prop="date"
              label="内容"
          >
            <template slot-scope="scope">
              <el-select v-model="scope.row.contentMediaId" placeholder="请选择">
                <el-option
                  v-for="item in scope.row.fileListOptions"
                  :key="item.id"
                  :label="item.media_name"
                  :value="item.id">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeWindowContent">取 消</el-button>
        <el-button type="primary" @click="confirmSetWindowContent">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {terminalListCol} from '../tableCol/terminalListCol'
import * as TerminalService from '@/views/terminal/service'
import * as service from '@/views/scene/service'
import * as FileService from '@/views/distribute/service'
import {suffixFileMapObj} from "@/utils/config";
import {saveWindowScene} from "@/views/scene/service";
export default {
  props: {
    show: {
      type: Boolean,
      default: false,
    },
    isGlobal: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      selectGlobalPutTerminal: [],
      selectTerminal: [],
      sceneBaseForm: {
        title: '',
        image: '',
        state: '0'
      },
      selectKeys: 0,
      checkIsCanSelect: () => {  return true },
      sceneForm: {
        name: ''
      },
      fileListOptions: [],
      searchObj: {
        name: '',
        groupId: '',
        page: 1,
        pageSize: 20
      },
      settingIndex: -1,
      uploadUrl: window.ajaxUploadUrl + '/common/fileApi/file',
      sceneWindowList: [],
      step: 1,
      terminalListCol,
      getList: TerminalService.getClientList,
      sceneSettingList: [{date: 'test'}],
      isShowWindowContent: false,
      layoutList: [],
      fileTypeMap: [],
      allFileList: [],
      singleClientList: [],
      editCache: {},
      editTerminalCache: []
    }
  },
  watch: {
    show(val) {
      this.$nextTick(() => {
        if (val) {
          this.getClientList()
        }
      })
    }
  },
  mounted() {
    this.fileTypeMap = [...suffixFileMapObj()]
    this.getAllFileList()
    this.getLayoutList()
    this.getSingleClientList()
  },
  methods: {
    changeGlobalPut() {

    },
    setTerminalTableDisabled(rows) {
      if(rows.id) {
        this.$refs.terminalTableRef.setOtherRowDisabled(rows)
      }
    },
    toggleGlobalRows(row, checkSelect=[]) {
      this.editTerminalCache = [...checkSelect]
      this.editCache = {...row}
      Object.keys(this.sceneBaseForm).forEach((keys) => {
        this.sceneBaseForm[keys] = row[keys]
      })
      this.sceneBaseForm.id = row.id
      console.log('checkSelect ---', checkSelect)
      // 统一投放
      if(checkSelect.length > 0 && checkSelect[0].state == 1) {
        this.$set(this.sceneBaseForm, 'state', '1')

        if(this.selectGlobalPutTerminal.length === 0) {
          this.selectGlobalPutTerminal = []
        }
        let tmp = {
          name: '全局投放',
          layout: checkSelect[0].layout,
          layoutId: checkSelect[0].layout_id,
          windows: [...checkSelect[0].layout.windows]
        }

        tmp.windows.forEach((item) => {
          item.layoutWindowId = item.layout_window_id
          item.mediaId = item.media_id
        })

        tmp.mediaName = checkSelect[0].layout.windows.map((child, childIndex) => {
          const { media_id } = child
          const findIndex = this.allFileList.findIndex((result) => {
            return result.id === media_id
          })
          if(findIndex !== -1) {
            if(childIndex === checkSelect[0].layout.windows.length - 1) {
              return `窗口${childIndex+1}: ${this.allFileList[findIndex].media_name}`
            } else {
              return `窗口${childIndex+1}: ${this.allFileList[findIndex].media_name},`
            }
          }
        })
        this.selectGlobalPutTerminal.push(tmp)

      } else {
        this.$set(this.sceneBaseForm, 'state', '0')
      }

      let clientTmpList = []
      checkSelect.forEach((item) => {
        clientTmpList.push({id: item.client_id})
      })
      this.$nextTick(() => {
        this.$refs.terminalTableRef.toggleRowSelectionMethods(clientTmpList);
      })
    },
    toggleRows(detail, row, checkSelect=[]) {
      console.log('编辑 ---', detail, row)
      this.editTerminalCache = [...checkSelect]
      this.editCache = {...detail}
      Object.keys(this.sceneBaseForm).forEach((keys) => {
        this.sceneBaseForm[keys] = detail[keys]
      })
      this.sceneBaseForm.id = detail.id

      this.$nextTick(() => {
        if(row.client_id) {
          let rowTmp = {
            id: row.client_id
          }
          this.$refs.terminalTableRef.toggleRowSelectionMethods([rowTmp]);
        }
      })
    },
    getAllFileList() {
      const params = {
        mediaType: '',
        page: 1,
        pageSize: 200000000
      }

      FileService.getFileList(params, {}).then((res) => {
        this.allFileList = res.data.records.slice()
      })
    },
    changeTypeMethods(val, index) {
      const filterData =  this.allFileList.filter((item) => {
        return item.media_type == val && item.file_type != 1
      })
      // this.fileListOptions = [...filterData]
      this.$set(this.sceneWindowList[index], 'fileListOptions', [...filterData])
      this.$set(this.sceneWindowList[index], 'contentMediaId', '')

    },
    changeLayoutId(row, model, index) {
      this.$set(this[model][index], 'layoutId', row.layoutId)
      this.$set(this[model][index], 'mediaName', '')
      this.selectTerminal.splice(0, 0)
      this.selectGlobalPutTerminal.splice(0, 0)

      this.selectKeys = this.selectKeys + 1
    },
    getLayoutList() {
      const params = {
        page: 1,
        pageSize: 200000
      }

      service.getLayoutList(params).then((res) => {
        this.layoutList = res.data.records.slice()
      })
    },
    getClientList() {
      const params = Object.assign({}, this.searchObj)
      this.$refs.terminalTableRef.queryData(params)
    },
    getSingleClientList() {
      const params = Object.assign({}, this.searchObj)
      TerminalService.getClientList(params).then((res) => {
        this.singleClientList = res.data.records.slice()
      })
    },
    changeFileRowMethods(rows) {
      console.log('changeFileRowMethods ---', rows)
      // 只有全局能多选终端
      if(this.isGlobal) {
        this.selectTerminal = [...rows]

        this.selectTerminal.forEach((item, key) => {
          if(!item.layout) {
            this.$set(item, 'layout', undefined)
          }
        })

        console.log('muti selectTerminal ---', this.selectTerminal)
      } else {
        if(rows.length >= 1) {
          this.$refs.terminalTableRef.setOtherRowDisabled(rows[0])
        } else {
          this.$refs.terminalTableRef.clearOtherRowDisabled()
        }
        this.selectTerminal = [...rows]
        this.selectTerminal.forEach((item) => {
          if(!item.layout) {
            this.$set(item, 'layout', undefined)
          }
        })
      }

      // 编辑赋值窗口布局
      if(this.editTerminalCache.length > 0) {
        if(this.sceneBaseForm.state == 0 || !this.isGlobal) {
          // 找到对应的终端赋值layout
          this.editTerminalCache.forEach((item) => {
            const findIndex = this.selectTerminal.findIndex((result) => {
              return result.id == item.client_id
            })

            if(findIndex !== -1) {
              this.selectTerminal[findIndex].layout = item.layout
              this.selectTerminal[findIndex].layoutId = item.layout_id

              console.log('item ----', item)
              this.$set(this.selectTerminal[findIndex], 'layoutId', item.layout_id)
              this.$set(this.selectTerminal[findIndex], 'mediaName', item.layout.windows.join(','))
            }
          })
        } else {

        }

        console.log('this.selectTerminal ---', this.selectTerminal)
      }
    },
    uploadSuccess(res) {
      this.sceneBaseForm.image = res.data[0].file
    },
    closeWindowContent() {
      this.sceneWindowList = []
      this.isShowWindowContent = false
    },
    confirmSetWindowContent() {
      // this.selectTerminal = []
      let tmpList = []
      for(let i = 0;i < this.sceneWindowList.length;i++) {
        if(!this.sceneWindowList[i].mediaType) {
          this.$message.error('请选择内容类型')
          return
        } else if(!this.sceneWindowList[i].contentMediaId) {
          this.$message.error('请选择内容')
          return
        }
      }
      this.sceneWindowList.forEach((item, key) => {
        // 文件ID查找文件名回显
        const findFileIndex = this.allFileList.findIndex((result) => {
          return result.id === item.contentMediaId
        })
        const tmp = {
          layoutWindowId: item.windowsId,
          mediaId: item.contentMediaId,
          windowIndex: key+1,
          mediaName: ''
        }

        if(findFileIndex !== -1) {
          tmp.mediaName = this.allFileList[findFileIndex].media_name
        }

        tmpList.push(tmp)
      })

      let allMediaName = []
      tmpList.forEach((item) => {
        allMediaName.push(`窗口${item.windowIndex}:${item.mediaName}`)
      })
      // 是否统一投放
      if(this.sceneBaseForm.state != 0) {
        this.selectGlobalPutTerminal[this.settingIndex].windows = tmpList.slice()
        this.$set(this.selectGlobalPutTerminal[this.settingIndex], 'mediaName', allMediaName.join(','))
        this.selectGlobalPutTerminal.splice(0, 0)
      } else {
        this.selectTerminal[this.settingIndex].windows = tmpList.slice()
        // console.log('this.selectTerminal[this.settingIndex] ----', this.selectTerminal[this.settingIndex])
        this.$set(this.selectTerminal[this.settingIndex], 'mediaName', allMediaName.join(','))
        this.selectTerminal.splice(0, 0)
      }

      console.log('this.selectTerminal ---', this.selectTerminal)
      this.isShowWindowContent = false
      this.sceneWindowList = []
    },
    handleClose() {
      this.selectTerminal = []
      this.selectGlobalPutTerminal = []
      this.editTerminalCache = []
      this.$emit('close')
      this.sceneBaseForm.title = ''
      this.sceneBaseForm.image = ''
      this.sceneBaseForm.state = '0'
      this.step = 1
    },
    startSettingWindow(row, index) {
      this.settingIndex = index
      // 布局id 查询布局详情
      const layoutId = row.layoutId
      const findLayoutIndex = this.layoutList.findIndex((item) => {
        return item.id == layoutId
      })
      if(findLayoutIndex !== -1) {
        const {horizontal, vertical, title} = this.layoutList[findLayoutIndex]

        // console.log('this.layoutList[findLayoutIndex] ---', this.layoutList[findLayoutIndex])

        let screenList = ['全屏', '二分屏', '三分屏', '四分屏', '九分屏']

        if(row.windows) {
          this.layoutList[findLayoutIndex].windows.forEach((item, key) => {
            const findItemIndex = this.allFileList.findIndex((result) => {
              return result.id == row.windows[key].mediaId
            })
            const mediaType = this.allFileList[findItemIndex].media_type.toString()
            const tmp = {
              ...item,
              horizontal,
              vertical,
              windowsId: item.id,
              title,
              mediaType,
              contentMediaId: row.windows[key].mediaId
            }
            this.sceneWindowList.push(tmp)
            const filterData =  this.allFileList.filter((item) => {
              return item.media_type == mediaType && item.file_type != 1
            })
            this.$set(this.sceneWindowList[key], 'fileListOptions', [...filterData])
          })
        } else {
          this.layoutList[findLayoutIndex].windows.forEach((item, key) => {
            const tmp = {
              ...item,
              horizontal,
              vertical,
              windowsId: item.id,
              title
            }
            this.sceneWindowList.push(tmp)
          })
        }

        if(screenList.indexOf(title) !== -1) {
          let horizontalXIndex = 0
          let horizontalYIndex = 0
          this.sceneWindowList.forEach((item) => {
            item.y = horizontalXIndex
            item.x = horizontalYIndex
            horizontalXIndex = horizontalXIndex + 1
            if(item.horizontal == horizontalXIndex) {
              horizontalXIndex = 0
              horizontalYIndex = horizontalYIndex + 1
            }
          })
        } else {
          this.sceneWindowList.forEach((item) => {
            delete item.horizontal
            delete item.vertical
          })
        }

      }
      this.settingRow = row
      this.isShowWindowContent = true
    },
    prevStepMethods() {
      this.step = this.step - 1
    },
    confirmSubmit() {
      if(this.step === 1) {
        if(this.selectTerminal.length === 0) {
          this.$message.error('请选择终端')
          return
        }
        // mediaName
        this.selectTerminal.forEach((item) => {
          if(item.layout && item.layout.windows.length > 0) {
            item.mediaName = item.layout.windows.map((child, childIndex) => {
              const { media_id } = child
              const findIndex = this.allFileList.findIndex((result) => {
                return result.id === media_id
              })
              if(findIndex !== -1) {
                if(childIndex === item.layout.windows.length - 1) {
                  return `窗口${childIndex+1}: ${this.allFileList[findIndex].media_name}`
                } else {
                  return `窗口${childIndex+1}: ${this.allFileList[findIndex].media_name},`
                }
              }
            })

            let windows = []
            item.layout.windows.forEach((child) => {
              let tmp = {
                layoutWindowId: child.layout_window_id,
                mediaId: child.media_id
              }
              windows.push(tmp)
            })


            item.windows = windows.slice()
          }
        })

        if(this.selectGlobalPutTerminal.length === 0) {
          let tmp = {
            name: '统一投放',
          }

          this.selectGlobalPutTerminal.push(tmp)
        }

        this.step += 1
      } else if(this.step === 2) {
        if(this.sceneBaseForm.state == 0) {
          for(let i = 0;i < this.selectTerminal.length;i++) {
            if(!this.selectTerminal[i].layoutId) {
              this.$message.error('请选择窗口布局')
              return
            } else if(!this.selectTerminal[i].mediaName) {
              this.$message.error('请配置窗口内容')
              return
            }
          }
        }

        if(this.sceneBaseForm.state == 1) {
          for(let i = 0;i < this.selectGlobalPutTerminal.length;i++) {
            if(!this.selectGlobalPutTerminal[i].layoutId) {
              this.$message.error('请选择窗口布局')
              return
            } else if(!this.selectGlobalPutTerminal[i].mediaName) {
              this.$message.error('请配置窗口内容')
              return
            }
          }
        }

        this.step += 1
      } else if(this.step === 3) {
        if(!this.sceneBaseForm.title) {
          this.$message.error('请输入场景名称')
          return
        }
        // else if(!this.sceneBaseForm.image) {
        //   this.$message.error('请上传场景缩略图')
        //   return
        // }
        // 保存提交场景
        const params = {
          ...this.sceneBaseForm,
          clients: [],
          type: 1,  // 1 全局 2 终端
        }

        if(!this.isGlobal) {
          params.type = 2
        }

        if(this.sceneBaseForm.state == 0) {
          this.selectTerminal.forEach((item) => {
            const tmp = {
              clientId: item.id,
              layoutId: item.layoutId,
              state: 0,
              windows: []
            }

            console.log('item.windows ---', item.windows)
            item.windows && item.windows.forEach((child) => {
              let tmpChild = {
                layoutWindowId: child.layoutWindowId,
                mediaId: child.mediaId
              }
              tmp.windows.push(tmpChild)
            })

            params.clients.push(tmp)
          })
        }

        // 全局投放
        if(this.sceneBaseForm.state == 1) {
          this.selectTerminal.forEach((item) => {
            const tmp = {
              clientId: item.id,
              layoutId: this.selectGlobalPutTerminal[0].layoutId,
              state: 1,
              windows: []
            }

            this.selectGlobalPutTerminal[0].windows.forEach((child) => {
              let tmpChild = {
                layoutWindowId: child.layoutWindowId,
                mediaId: child.mediaId
              }
              tmp.windows.push(tmpChild)
            })

            params.clients.push(tmp)
          })
        }
        console.log('params ---', params)

        delete params.state
        service.saveWindowScene(params).then(() => {
          this.$message.success('保存成功')
          this.step = 1
          this.selectTerminal = []
          this.selectGlobalPutTerminal = []
          this.editTerminalCache = []
          this.sceneBaseForm.state = '0'
          this.$emit('submitSuccess')
        })

      }
    }
  }
}
</script>

<style scoped lang="scss">
  .row-container{
    display: flex;

    .col-container{
      margin: 3px;
      width: 15px;
      height: 15px;
      border: 1px solid #DCDFE6;
    }

    .col-container-active{
      background-color: #409EFF;
    }
  }
</style>
